package com.zwh.se.io;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * @author zwh
 * 一个获取文件MD5码的demo
 */
public class FIleMD5 {
    public static void main(String[] args) {
        File file = new File("file/output.txt");
        if (!file.exists() || !file.isFile()) {
            System.out.println("文件不存在或提供的为文件夹");
            return;
        }
        MessageDigest messageDigest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) > 0) {
                messageDigest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] data = messageDigest.digest();
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append("0123456789ABCDEF".toCharArray()[(b >> 4) & 0xF]);
            r.append("0123456789ABCDEF".toCharArray()[(b & 0xF)]);
        }
        System.out.println("此文件的MD5码为:" + r.toString());
    }
}
